<?php

if(!defined('IN_ECS'))
{
	die('Hacking attempt');
}

if(isset($set_modules) && $set_modules == TRUE)
{ 
	$i = (isset($modules)) ? count($modules) : 0;
	
	$modules[$i]['code'] = 'ecshop';
	
	$modules[$i]['name'] = 'ECSHOP';
	
	$modules[$i]['version'] = '2.0';
	
	$modules[$i]['author'] = 'ECSHOP R&D TEAM';
	
	$modules[$i]['website'] = 'http://www.ecshop.com';
	
	return;
}

require_once ROOT_PATH.'includes/modules/integrates/integrate.php';

class ecshop extends integrate
{
	var $is_ecshop = 1;
	
	function __construct($cfg)
	{
		$this->ecshop($cfg);
	}
	
	function ecshop($cfg)
	{
		parent::integrate(array());
		$this->user_table = 'users';
		$this->field_id = 'user_id';
		$this->field_name = 'user_name';
		$this->field_pass = 'password';
		$this->field_email = 'email';
		$this->field_gender = 'sex';
		$this->field_bday = 'birthday';
		$this->field_reg_date = 'reg_time';
		$this->is_ecshop = 1;
	}
	
	function check_user($username,$password = null)
	{
		if($this->charset != 'UTF8')			//当前字符集不是utf8
		{
			$post_username = ecs_iconv('UTF8',$this->charset,$username);
		}
		else									//是utf8
		{
			$post_username = $username;
		}
		
		if($password === null)					//密码为空
		{
			$sql = "SELECT " . $this->field_id . 
					" FROM " . $this->table($this->user_table) .
					" WHERE " . $this->field_name . "='" . $post_username ."'";
			
			return $this->db->getOne($sql);
		}
		else									//密码不为空
		{
			$sql = "SELECT user_id,password,salt " .
					" FROM " . $this->table($this->user_table).
					" WHERE user_name='$post_username'";
			$row = $this->db->getRow($sql);		//返回对应用户的相关信息数组
			
			if(empty($row))						//没有此用户则直接返回
			{
				return 0;
			}
			
			if(empty($row['salt']))				//密码种子为空
			{
				if($row['password'] != $this->compile_password(array('password'=>$password)))	//依照各种密码加密方式生成密码与数据库中的密码不相符
				{
					return 0;					//直接返回
				}
				else 
				{
					return $row['user_id'];		//密码相符,返回该用户id
				}
			}
			else 								//有密码种子
			{
				$encrypt_type = substr($row['salt'], 0,1);
				$encrypt_salt = substr($row['salt'], 1);
				
				$encrypt_password = '';
				switch($encrypt_type)
				{
					case ENCRYPT_ZC :
						$encrypt_password = md5($encrypt_salt.$password);
						break;
						
					case ENCRYPT_UC:
						$encrypt_password = md5(md5($password).$encrypt_salt);
						break;
						
					default:
						$encrypt_password = '';
				}
				
				if($row['password'] != $encrypt_password)
				{
					return 0;
				}
				
				$sql = "UPDATE " . $this->table($this->user_table) .
						" SET password = '" . $this->compile_password(array('password'=>$password)) . "',salt=''".
						" WHERE user_id = '$row[user_id]'";
				
				$this->db->query($sql);
			}
		}
	}
	
}

